﻿using System;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;

using LTJ.Common;
using LTJ.Config;
using LTJ.Config.Provider;
using LTJ.Entity;
using System.Text.RegularExpressions;

namespace LTJ.FrameWork
{
    public class UserPage : System.Web.UI.Page
    {
        /// <summary>
        /// 更改企业ID
        /// </summary>
        protected int changeCID = SASRequest.GetInt("changecid", 0);
        /// <summary>
        /// 配置信息
        /// </summary>
        protected internal GeneralConfigInfo config;
        /// <summary>
        /// 在线用户信息
        /// </summary>
        protected internal OnlineUserInfo oluserinfo;
        /// <summary>
        /// 当前用户的用户ID
        /// </summary>
        protected internal int userid;
        /// <summary>
        /// 当前用户的在线表ID
        /// </summary>
        protected internal int olid;
        /// <summary>
        /// 当前页面是否被POST请求
        /// </summary>
        protected internal bool ispost;
        /// <summary>
        /// 是否跳转
        /// </summary>
        protected internal bool isrefresh = false;
        /// <summary>
        /// 跳转时间
        /// </summary>
        private int refreshsec = 0;
        /// <summary>
        /// 跳转连接
        /// </summary>
        private string refreshurl = "";
        /// <summary>
        /// 当前页面是否被GET请求
        /// </summary>
        protected internal bool isget;
        /// <summary>
        /// 当前页面标题
        /// </summary>
        protected internal string pagetitle = "页面";
        /// <summary>
        /// 当前日期
        /// </summary>
        protected internal string nowdate;
        /// <summary>
        /// 当前时间
        /// </summary>
        protected internal string nowtime;
        /// <summary>
        /// 当前日期时间
        /// </summary>
        protected internal string nowdatetime;

        protected internal string username = "";
        /// <summary>
        /// 当前用户实体信息
        /// </summary>
        protected UserInfo userinfo = new UserInfo();
        /// <summary>
        /// 当前企业信息
        /// </summary>
        protected CompanyInfo companyinfo = new CompanyInfo();
        /// <summary>
        /// 当前企业管理员权限
        /// </summary>
        protected Authority userauth = new Authority();
        protected bool ischange = false;

        /// <summary>
        /// 控件初始化时计算执行时间
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            m_processtime = (Environment.TickCount - m_starttick) / 1000;
            base.OnInit(e);
        }

        /// <summary>
        /// 得到当前页面的载入时间供模板中调用(单位:毫秒)
        /// </summary>
        /// <returns>当前页面的载入时间</returns>
        public float Processtime
        {
            get { return m_processtime; }
        }

        /// <summary>
        /// 当前页面开始载入时间(毫秒)
        /// </summary>
        public float m_starttick = Environment.TickCount;

        /// <summary>
        /// 当前页面执行时间(毫秒)
        /// </summary>
        public float m_processtime;

        public UserPage()
        {
            if (!Page.IsPostBack)
            {
                this.RegisterAdminPageClientScriptBlock();
            }

            config = GeneralConfigs.GetConfig();
            if (changeCID <= 0) changeCID = Utils.StrToInt(FrameWorkUtil.GetCookie("usercid"), 0);
            userid = Utils.StrToInt(FrameWork.FrameWorkUtil.GetCookie("userid"), -1);
            username = FrameWorkUtil.GetCookie("username");
            string usercode = FrameWorkUtil.GetCookie("vercode");
            
            if (SASRequest.GetPageName() != "userlogin.aspx")
            {
                if (userid == -1)
                {
                    Context.Response.Redirect(config.UserManagerUrl + "userlogin.aspx");
                    return;
                }
                userinfo = Users.GetUser(userid);
                userinfo.cid = changeCID;

                if (config.SpecialLogin == 1)
                {
                    if (usercode.Trim().ToLower() != userinfo.olcode.Trim().ToLower())
                    {
                        Context.Response.Redirect(config.UserManagerUrl + "userlogin.aspx?result=5&olcode=" + usercode);
                        return;
                    }
                }

                if (userinfo.cid == 0 || userinfo.status == 0 || FrameWorkUtil.GetCookiePassword(FrameWorkUtil.GetCookie("password"), config.Passwordkey) != userinfo.pass.ToString())
                {
                    Context.Response.Redirect(config.UserManagerUrl + "userlogin.aspx");
                    return;
                }
                else
                {
                    FrameWorkUtil.WriteDYJUserCookies(userinfo);
                }
                
                companyinfo = Companys.GetCompanyByID(userinfo.cid);
                userauth = Users.GetAuthInfoCache(companyinfo.id, userid);
            }
            try
            {
                oluserinfo = OnlineUsers.UpdateInfo(config.Passwordkey, config.Onlinetimeout);
            }
            catch
            {
                System.Threading.Thread.Sleep(2000);
                oluserinfo = OnlineUsers.UpdateInfo(config.Passwordkey, config.Onlinetimeout);
            }
            if (userid != -1)
            {
                OnlineUsers.UpdateOnlineTime(config.Oltimespan, userid);
            }
            olid = oluserinfo.id;
        }

        /// <summary>
        /// 操作动作判断
        /// </summary>
        public bool OpAction(OprateAction aotype)
        {
            string PageUrl = SASRequest.GetUrl();

            if (!string.IsNullOrEmpty(PageUrl)) PageUrl = Utils.ReplaceString(PageUrl, "http://" + SASRequest.GetHost() + "/", "", true);

            Regex objStr = new Regex(@"," + @PageUrl.Replace("?", @"\?") + @"\|([a-zA-Z]+?\|)+\d\,", RegexOptions.None);
            Match m = objStr.Match("," + companyinfo.Authoritys);
            if (!m.Success) return false;
            Match sm = objStr.Match("," + userauth.Authoritys);
            if (!m.Success) return false;
            if (!m.Groups[0].Value.Contains("|" + aotype + "|")) return false;
            if (!sm.Groups[0].Value.Contains("|" + aotype + "|")) return false;
            return true;
        }

        /// <summary>
        /// 操作动作判断
        /// </summary>
        public bool OpAction(OprateAction aotype,string PageUrl)
        {
            Regex objStr = new Regex(@"," + @PageUrl.Replace("?", @"\?") + @"\|([a-zA-Z]+?\|)+\d\,", RegexOptions.None);
            Match m = objStr.Match("," + companyinfo.Authoritys);
            if (!m.Success) return false;
            Match sm = objStr.Match("," + userauth.Authoritys);
            if (!m.Success) return false;
            if (!m.Groups[0].Value.Contains("|" + aotype + "|")) return false;
            if (!sm.Groups[0].Value.Contains("|" + aotype + "|")) return false;
            return true;
        }

        /// <summary>
        /// 注册提示信息JS脚本
        /// </summary>
        public void RegisterAdminPageClientScriptBlock()
        {
            string script = "<div id=\"success\" style=\"position:absolute;z-index:300;height:120px;width:284px;left:50%;top:50%;margin-left:-150px;margin-top:-80px;\">\r\n" +
                "	<div id=\"Layer2\" style=\"position:absolute;z-index:300;width:270px;height:90px;background-color: #FFFFFF;border:solid #000000 1px;font-size:14px;\">\r\n" +
                "		<div id=\"Layer4\" style=\"height:26px;background:#f1f1f1;line-height:26px;padding:0px 3px 0px 3px;font-weight:bolder;\">操作提示</div>\r\n" +
                "		<div id=\"Layer5\" style=\"height:64px;line-height:150%;padding:0px 3px 0px 3px;\" align=\"center\"><BR /><table><tr><td valign=top><img border=\"0\" src=\"../images/ajax_loading.gif\"  /></td><td valign=middle style=\"font-size: 14px;\" >正在执行当前操作, 请稍等...<BR /></td></tr></table><BR /></div>\r\n" +
                "	</div>\r\n" +
                "	<div id=\"Layer3\" style=\"position:absolute;width:270px;height:90px;z-index:299;left:4px;top:5px;background-color: #E8E8E8;\"></div>\r\n" +
                "</div>\r\n" +
                "<script> \r\n" +
                "document.getElementById('success').style.display = \"none\"; \r\n" +
                "</script> \r\n" ;

            ClientScript.RegisterClientScriptBlock(this.GetType(), "Page", script);
        }

        public new void RegisterStartupScript(string key, string scriptstr)
        {
            key = key.ToLower();
            if ((key == "pagetemplate") || (key == "page"))
            {
                string script = "";

                if (key == "page")
                {
                    script = "<script> \r\n" +
                        "var bar=0;\r\n" +
                        "document.getElementById('success').style.display = \"block\";  \r\n" +
                        "document.getElementById('Layer5').innerHTML ='<BR>操作成功执行<BR>';  \r\n" +
                        "count() ; \r\n" +
                        "function count(){ \r\n" +
                        "bar=bar+4; \r\n" +
                        "if (bar<99) \r\n" +
                        "{setTimeout(\"count()\",100);} \r\n" +
                        "else { \r\n" +
                        "document.getElementById('success').style.display = \"none\";HideOverSels('success'); \r\n" +
                        scriptstr + "} \r\n" +
                        "} \r\n" +
                        "</script> \r\n" +
                        "<script> window.onload = function(){HideOverSels('success')};</script>\r\n";
                }

                if (key == "pagetemplate")
                {
                    script = "<script> \r\n" +
                        "var bar=0;\r\n success.style.display = \"block\";  \r\n" +
                        "document.getElementById('Layer5').innerHTML = '<BR>" + scriptstr + "<BR>';  \r\n" +
                        "count() ; \r\n" +
                        "function count(){ \r\n" +
                        "bar=bar+4; \r\n" +
                        "if (bar<99) \r\n" +
                        "{setTimeout(\"count()\",100);} \r\n" +
                        "else { \r\n" +
                        "document.getElementById('success').style.display = \"none\";HideOverSels('success'); \r\n" +
                        "}} \r\n" +
                        "</script> \r\n" +
                        "<script> window.onload = function(){HideOverSels('success')};</script>\r\n";
                }
                ClientScript.RegisterStartupScript(this.GetType(), key, script);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), key, scriptstr);
            }
        }

        public void CallBaseRegisterStartupScript(string key, string scriptstr)
        {
            ClientScript.RegisterStartupScript(this.GetType(), key, scriptstr);
        }

        private bool saveState = false;

        private bool IsRestore
        {
            get
            {
                if (Request.QueryString["IsRestore"] != null && Request.QueryString["IsRestore"] == "1" && Request.Form["__VIEWSTATE"] == null)
                    return true;
                else
                    return false;
            }
        }

        private string RestoreKey
        {
            get { return Request.QueryString["key"]; }
        }

        public bool SavePageState
        {
            get { return this.saveState; }
            set { this.saveState = value; }
        }

        private NameValueCollection postData = null;

        private NameValueCollection PostData
        {
            get
            {
                if (this.IsRestore)
                    return this.postData;
                return Request.Form;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (this.IsRestore)
            {
                ArrayList modifiedControls = new ArrayList();
                foreach (string key in PostData.AllKeys)
                {
                    System.Web.UI.Control control = FindControl(key);
                    if (control is IPostBackDataHandler)
                        if (((IPostBackDataHandler)control).LoadPostData(key, PostData))
                            modifiedControls.Add(control);
                }
                // 发生 PostDataChanged 事件在所有已变动的控件上:
                foreach (IPostBackDataHandler control in modifiedControls)
                    control.RaisePostDataChangedEvent();
            }
            base.OnLoad(e);
        }

        #region 调用自定义的方法对VIEWSTATE进行操作

        protected void SASLogicSavePageState(object viewState)
        {
            string keyid = userid + "_" + this.GetType().Name.Trim();
            SASControlContainer dcc = SASControlContainer.GetContainer();
            dcc.AddNormalComponent(keyid, viewState);
        }

        protected object DiscuzForumLoadPageState()
        {
            string keyid = userid + "_" + this.GetType().Name.Trim();
            SASControlContainer dcc = SASControlContainer.GetContainer();
            object viewState = (object)dcc.GetNormalComponentDataObject(keyid);
            dcc.RemoveComponentByName(keyid);
            if (viewState != null) return viewState;
            else return null;
        }

        #endregion

        #region 把VIEWSTATE以组件的形式存入容器

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            base.SavePageStateToPersistenceMedium(viewState);
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            object o = new object();
            try
            {
                o = base.LoadPageStateFromPersistenceMedium();
            }
            catch
            {
                o = null;
            }
            return o;
        }

        #endregion
    }
}
